<?php


namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class SignUp extends Model
{
    // 表名
    protected $name = 'signup';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    /**
     * @var null|static 实例对象
     */
    protected static $instance = null;

    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) self::$instance = new self($options);

        return self::$instance;
    }

    public function userHasOne()
    {
        return $this->hasOne(User::class, 'id', 'user_id')
            ->field('id, nickname, avatar')
            ->bind('nickname,avatar');
    }

    public function activityHasOne()
    {
        return $this->hasOne(Activity::class, 'id', 'id')
            ->field('id, title, image, startdate, endtime')
            ->bind('title,image,startdate,endtime');
    }

    /**
     * 活动报名打卡
     * @param int $activity_id
     * @param int $user_id
     * @param int $number
     * @return bool
     * @throws
     */
    public function userApplication(int $activity_id, int $user_id, int $number): bool
    {
        $save = [];
        $save['number'] = $number;
        if (!$rows = $this->where(['activity_id' => $activity_id, 'user_id' => $user_id])->whereTime('createtime', 'today')->find()) {
            $save['activity_id'] = $activity_id;
            $save['user_id'] = $user_id;
            $save['createtime'] = date('Y-m-d H:i:s');
        } else {
            $save['save_number'] = ($rows['save_number'] + 1);
        }
        Db::startTrans();
        try {
            $response = $this->allowField(true)->save($save, array_filter(['id' => $rows['id'] ?? 0]));
            if ($response) {
                Db::commit();
                return true;
            }
            throw new Exception('报名失败');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }
}